//package com.letoken.platform.admin.controller;
//
//import java.time.LocalDateTime;
//
//import cn.hutool.core.collection.CollUtil;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.letoken.platform.admin.service.AdminMenuService;
//import com.letoken.platform.admin.service.AdminRoleMenuService;
//import com.letoken.platform.pub.annotation.auth.Permission;
//import com.letoken.platform.pub.enums.LetokenApiResponseEnum;
//import com.letoken.platform.pub.exception.ApiServiceException;
//import com.letoken.platform.pub.reflect.ReflectionInfo;
//import com.letoken.platform.pub.res.ApiResponse;
//import com.letoken.platform.pub.util.BeanUtil;
//import com.letoken.platform.repo.admin.dao.AdminMenuMapper;
//import com.letoken.platform.repo.admin.dao.AdminRoleMapper;
//import com.letoken.platform.repo.admin.dao.AdminRoleMenuMapper;
//import com.letoken.platform.repo.admin.dao.AdminUserMapper;
//import com.letoken.platform.repo.admin.manager.AdminUserManager;
//import com.letoken.platform.repo.admin.po.AdminMenu;
//import com.letoken.platform.repo.admin.po.AdminRole;
//import com.letoken.platform.repo.admin.po.AdminRoleMenu;
//import com.letoken.platform.repo.admin.po.AdminUser;
//import com.letoken.platform.repo.admin.redis.AdminUserInfoRedis;
//import com.letoken.platform.repo.admin.req.menu.UpdatePermissionReq;
//import com.letoken.platform.repo.admin.res.system.QueryAdminMenuTreeRes;
//import com.letoken.platform.repo.admin.res.user.AdminUserInfoRes;
//import com.letoken.platform.repo.admin.res.user.AdminUserRoleInfoRes;
//import com.letoken.platform.repo.admin.util.MenuTreeUtil;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import lombok.extern.log4j.Log4j2;
//import org.apache.commons.lang.StringUtils;
//import org.apache.commons.lang3.ObjectUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.context.WebApplicationContext;
//import org.springframework.web.method.HandlerMethod;
//import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
//import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
//import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
//import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
//
//import java.lang.reflect.Method;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//import java.util.stream.Collectors;
//
//
///**
// * @author wyl
// * @date 2023/2/22 15:31
// * @Version 1.0
// */
//@RestController
//@RequestMapping("/permission")
//@Api(tags = "权限反射控制器")
//@Log4j2
//public class ProjectReflectionController {
//    @Autowired
//    WebApplicationContext applicationContext;
//
//    @Autowired
//    private AdminMenuMapper adminMenuMapper;
//
//    @Autowired
//    private AdminRoleMapper adminRoleMapper;
//
//    @Autowired
//    private AdminRoleMenuMapper roleMenuMapper;
//
//    @Autowired
//    private AdminMenuService adminMenuService;
//
//    @Autowired
//    AdminUserMapper adminUserMapper;
//
//    @Autowired
//    private AdminRoleMenuService roleMenuService;
//
//    @Autowired
//    private AdminRoleMenuMapper adminRoleMenuMapper;
//
//    @Autowired
//    private AdminUserManager adminUserManager;
//
//    @Autowired
//    private AdminRoleMapper roleMapper;
//
//    //控制器类信息list
//    public static List<ReflectionInfo> reflectInfoList;
//    /**
//     * 初始化controller类信息
//     * RequestMappingHandlerMapping在controller中使用
//     *
//     * @return
//     */
//    @PostMapping("/go")
//    @ApiOperation(value = "权限", notes = "权限")
//    public void setReflectInfoList() {
//        try {
//            reflectInfoList = new ArrayList<>();
//            RequestMappingHandlerMapping mapping = applicationContext.getBean("requestMappingHandlerMapping",RequestMappingHandlerMapping.class);
//            // 获取url与类和方法的对应信息
//            Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
//            for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
//                RequestMappingInfo info = m.getKey();
//                HandlerMethod method = m.getValue();
//                PatternsRequestCondition p = info.getPatternsCondition();
//                ReflectionInfo ref = new ReflectionInfo();
//                for (String url : p.getPatterns()) {
//                    ref.setUrl(url);
//                }
//                // 类名
//                ref.setClassName(method.getMethod().getDeclaringClass().getName());
//                // 方法名
//                ref.setMethod(method.getMethod().getName());
//                RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
//                for (RequestMethod requestMethod : methodsCondition.getMethods()) {
//                    ref.setType(requestMethod.toString());
//                }
//                reflectInfoList.add(ref);
//            }
//        }catch (Exception e) {
//            log.error(e.getMessage());
//            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_ORDER_002);
//        }
//        finally {
//            insReqIdentifying();
//            reflectInfoList = new ArrayList<>();
//        }
//    }
//
//    /**
//     * 根据请求url获取方法上的注释名称
//     *
//     * @param url 路径标识
//     * @return
//     */
//    public List<Object> getMethodApiOperation(String url) {
//        Class cls = null;
//        if (null == reflectInfoList || reflectInfoList.isEmpty()) {
//            throw new RuntimeException("init reflectInfoList error");
//        }
//        for (ReflectionInfo entity : reflectInfoList) {
//            if (entity.getUrl().equals(url)) {
//                try {
//                    cls = Class.forName(entity.getClassName());
//                } catch (ClassNotFoundException e) {
//                    e.printStackTrace();
//                }
//                assert cls != null;
//                Method[] ms = cls.getDeclaredMethods();
//                List<Object> array = new ArrayList<>();
//                for (Method m : ms) {
//                    if (m.getName().equals(entity.getMethod())) {
//                        Permission p = m.getAnnotation(Permission.class);
//                        if (p == null) {
//                            return null;
//                        }
//                        array.add(p.menuName());
//                        String uri = p.uri();
//                        if (StringUtils.isNotBlank(uri)) {
//                            array.add(p.uri());
//                        } else {
//                            array.add(url);
//                        }
//                        array.add(p.type());
//                        array.add(p.pid());
//                        array.add(p.level());
//                        return array;
//                    }
//                }
//            }
//        }
//        return null;
//    }
//
//    /**
//     * 预热权限
//     */
//    @Transactional(rollbackFor = Exception.class)
//    public ApiResponse insReqIdentifying() {
//
//        List<AdminMenu> adminMenuList = new ArrayList<>();
//        for (ReflectionInfo reflectionInfo : reflectInfoList) {
//            List<Object> array = this.getMethodApiOperation(reflectionInfo.getUrl());
//            if (CollUtil.isEmpty(array)) {
//                continue;
//            }
//            String uri = (String) array.get(1);
//            uri = uri.trim();
//
//            if (StringUtils.isNotBlank(uri)) {
//                LambdaQueryWrapper<AdminMenu> queryWrapper = Wrappers.lambdaQuery();
//                queryWrapper.eq(AdminMenu::getUri, uri);
//                AdminMenu selectOne = adminMenuMapper.selectOne(queryWrapper);
//                if (ObjectUtils.isEmpty(selectOne)) {
//                    AdminMenu adminMenu = new AdminMenu();
//                    adminMenu.setName((String) array.get(0));
//                    adminMenu.setUri(uri);
//                    adminMenu.setType((Integer) array.get(2));
//                    adminMenu.setPid((Integer) array.get(3));
//                    adminMenu.setExamineStatus(0);
//                    adminMenu.setLevel((Integer) array.get(4));
//                    adminMenu.setSort(1);
//                    adminMenu.setDescription(adminMenu.getName());
//                    adminMenu.setCreateTime(LocalDateTime.now());
//                    adminMenu.setUpdateTime(LocalDateTime.now());
//                    adminMenu.setIsDelete(0);
//                    adminMenuList.add(adminMenu);
//                }
//            }
//        }
//        if (CollUtil.isNotEmpty(adminMenuList)){
//            adminMenuService.saveBatch(adminMenuList);
//            //给超级管理员分配所有权限
//            List<AdminMenu> adminMenus = adminMenuMapper.selectList(null);
//            LambdaQueryWrapper<AdminRoleMenu> queryWrapper = Wrappers.lambdaQuery();
//            queryWrapper.eq(AdminRoleMenu::getAdminRoleId, 1);
//            roleMenuMapper.delete(queryWrapper);
//            List<AdminRoleMenu> adminRoleMenuList = new ArrayList<>();
//            for (AdminMenu adminMenu : adminMenus) {
//                AdminRoleMenu adminRoleMenu = new AdminRoleMenu();
//                adminRoleMenu.setAdminRoleId(1);
//                adminRoleMenu.setAdminMenuId(adminMenu.getAdminMenuId());
//                adminRoleMenu.setDeleteStatus(0);
//                adminRoleMenu.setCreateTime(LocalDateTime.now());
//                adminRoleMenu.setUpdateTime(LocalDateTime.now());
//                adminRoleMenu.setIsDelete(0);
//                adminRoleMenuList.add(adminRoleMenu);
//            }
//            roleMenuService.saveBatch(adminRoleMenuList);
//            List<QueryAdminMenuTreeRes> userMenuList = adminRoleMenuMapper.selectMenuListByRole(1);
//            List<QueryAdminMenuTreeRes> treeList = MenuTreeUtil.buildMenuTree(userMenuList);
//            List<String> menuUriList = adminRoleMenuMapper.selectMenuListByAdminUserRoleId(1);
//            List<AdminUser> adminUserList = adminUserManager.queryUserListByRoleId(1);
//            AdminRole adminRole = roleMapper.selectById(1);
//            for (AdminUser adminUser : adminUserList) {
//                AdminUserInfoRes adminUserInfo = AdminUserInfoRedis.me().getAdminUserInfo(adminUser.getToken());
//                if (adminUserInfo == null){
//                    adminUserInfo = new AdminUserInfoRes();
//                    BeanUtil.quickCopy(adminUser, adminUserInfo);
//                    AdminUserRoleInfoRes roleInfo = new AdminUserRoleInfoRes();
//                    BeanUtil.quickCopy(roleInfo,adminRole);
//                    adminUserInfo.setRoleInfo(roleInfo);
//                }
//                adminUserInfo.setMenuUriList(menuUriList);
//                adminUserInfo.setTree(treeList);
//                //token作为key，AdminUserInfo作为value，缓存用户信息。
//                AdminUserInfoRedis.me().setObject(adminUser.getToken(), adminUserInfo);
//            }
//            List<Integer> idList = adminMenuList.stream().map(AdminMenu::getAdminMenuId).collect(Collectors.toList());
//            List<Integer> menuPidList = adminMenuMapper.selectIdByPidList(idList);
//            List<Integer> menuIdList = adminMenuMapper.selectPidByIdList(idList);
//            idList.addAll(menuPidList);
//            idList.addAll(menuIdList);
//            idList = idList.stream().distinct().collect(Collectors.toList());
//            List<Integer> roleIdList = adminRoleMenuMapper.selectRoleIdListByMenuId(menuIdList);
//            for (Integer roleId : roleIdList) {
//                if (roleId != 1){
//                    UpdatePermissionReq req = new UpdatePermissionReq();
//                    req.setAdminRoleId(roleId);
//                    req.setAdminMenuIdList(idList);
//                    try {
//                        adminMenuService.updatePermission(req);
//                    }catch (Exception e){
//                        System.out.println(e.getMessage());
//                    }
//                }
//            }
//        }
//
//
//        return ApiResponse.create(null);
//    }
//
////    @NotAuthorization
////    @PostMapping("/white")
////    @ApiOperation(value = "白名单", notes = "白名单")
////    public void addWhiteAdminUserName() {
////        List<AdminUser> adminUsers = adminUserMapper.selectList(null);
////        for (AdminUser adminUser : adminUsers) {
////            if (adminUser.getLocked() == 0){
////                AdminLoginWhiteListRedis.me().addAdminUserName(adminUser.getUsername());
////            }
////        }
////    }
//}
